<template>
  <!-- 歌单路由 -->
  <div id="songlist">
    <NavHead @handle-category="handleCategory"></NavHead>
    <SongListItem
      :song-list="songList"
      @song-list-item-click="songListItemClick"
    ></SongListItem>
    <Page
      :total-data="totalData"
      :page-num="20"
      @change-page="changePage"
    ></Page>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  onMounted,
  provide,
  toRefs,
  ref,
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import NavHead from "@/components/songlistChild/NavHead.vue";
import SongListItem from "@/components/songlistitem/SongListItem.vue";
import Page from "@/components/page/Page.vue";
import {
  handleSongListCategory,
  handleSongList,
} from "@/network/songlist/songlist";
export default defineComponent({
  name: "SongList",
  components: {
    NavHead,
    SongListItem,
    Page,
  },
  setup() {
    const router = useRouter();
    const store = useStore();
    let categorys = ref([]); // 歌单分类
    let data = reactive({
      songListParams: {
        offset: 0,
        limit: 20,
        order: "hot",
        cat: "全部",
      }, // 获取歌单的参数
      songList: [], // 歌单数据
      totalData: 0, // 歌单总数据量
    });
    provide("categorys", categorys); // provide只支持传递ref数据

    onMounted(() => {
      getCategorys();
      getSongList(data.songListParams);
    });

    // 获取歌单分类
    let getCategorys = async () => {
      let css = [];
      let res = await handleSongListCategory();
      for (let key in res.categories) {
        let cs = { k: res.categories[key], v: [] };

        res.sub.forEach((element) => {
          if (element.category == key) {
            cs.v.push(element);
          }
        });

        css.push(cs);
      }
      categorys.value = css;
    };

    // 获取歌单
    let getSongList = async (params) => {
      const res = await handleSongList(params);
      data.songList = res.playlists;

      data.totalData = res.total;
    };

    // 子组件改变页码的回调
    let changePage = (page) => {
      // 改变页面之后要重新进行数据的请求
      data.songListParams.offset = (page - 1) * 20;
      getSongList(data.songListParams);
      // 滚动到最上面的位置
      document.documentElement.scrollTop = 0;
    };

    // 处理子组件分类歌单的点击事件
    let handleCategory = (category) => {
      data.songListParams.cat = category;
      getSongList(data.songListParams);
    };

    // 子组件的SongListItem的点击事件
    let songListItemClick = (item) => {
      store.dispatch("saveSongListDetail", item);
      router.push("/playlist");
    };

    return {
      ...toRefs(data),
      changePage,
      handleCategory,
      songListItemClick,
    };
  }
});
</script>
<style scoped>
#songlist {
  padding: 20px;
  background-color: #fff;
}
</style>
